<template>
  <div class="goods">
    <div class="goodsdetail">
      <div class="img">
        <el-image style="width: 398px; height: 398px" :src="imgU" width="398px" height="398px"></el-image>
      </div>
      <div class="detail">
        <div class="ziti">
          <h4 class="title col-12">{{ goodsDetail.name }}</h4>
          <p class="col-12">{{ goodsDetail.intro }}</p>
        </div>
        <div class="price col-12">
          价格：
          <em class="text-primary">{{ goodsDetail.price }} 元</em>
        </div>
        <div class="amout col-12">
          <p>
            数量：
            <el-input-number v-model="num" @change="handleChange" :min="1" :max="10" label="描述文字"></el-input-number>
          </p>
          <p>上市时间：{{ goodsDetail.pubdate }}</p>
          <p>热销指数：{{ goodsDetail.star }} ⭐</p>
        </div>
        <div class="dropdown-divider col-12"></div>
        <div class="buy">
          <div class="row">
            <el-row>
              <el-button class="join" type="danger" @click="addcart">加入购物车</el-button>
              <el-button type="success" class="buyin" @click="addorder">购买</el-button>
              <el-button
                type="primary"
                v-if="isF == 0"
                @click="goodsFavoritesByGid(goodsDetail.flag, goodsDetail.id)"
              >收藏</el-button>
              <el-button
                type="waring"
                v-if="isF == 1"
                @click="goodsUnFavoritesByGid(goodsDetail.flag, goodsDetail.id)"
              >取消收藏</el-button>
            </el-row>
          </div>
        </div>
      </div>
    </div>
    <div>
      <div class="form-group">
        <div>
          <label>评论内容：</label>
          <textarea class="form-control" v-model="content"></textarea>
        </div>
        <input type="button" value="发表评论" class="btn btn-primary input" @click="addmessage" />
      </div>
      <el-table :data="Messagelist" border height="300" style="width: 70%; margin: auto">
        <el-table-column prop="name" label="用户" />
        <el-table-column prop="title" label="评论" />
      </el-table>
    </div>
  </div>
  <preOrder 
        v-if='preOrderVisible===true' 
        :preOrderVisible="preOrderVisible" 
        :goodsId="id"
        :goodsNum="num"
        @onClosePreOrderDialog="closePreOrderDialogVisible"
    ></preOrder>
</template>

<script>
import { reactive, toRefs, onMounted } from "vue";
import axios from "axios";
import { useRoute } from "vue-router";
import { ElNotification } from "element-plus";
import preOrder from './preOrder.vue'

function loadData(state) {
  const params = {
    id: state.id,
  };
  axios({
    url: "/getGoodsById",
    method: "get",
    params: params,
  }).then((res) => {
    // if (res.data.code == 200) {
    console.log(res.data);
    state.goodsDetail = res.data.data;
    const imagesURL = import.meta.env.VITE_APP_URL + "/images/";
    state.imgU = imagesURL + state.goodsDetail.picture;
    // this.imagesURL = + "/images/"
    // }
  });
}

//加入购物车
function useAddcart(state) {
  const addcart = () => {
    if (state.username == null) {
      ElNotification({
        title: "请先登录",
        message: "请先登录",
        type: "error",
        duration: 2000,
      });
    } else {
      const params = {
        gid: state.id,
        price: state.goodsDetail.price,
        num: "1",
        username: state.username,
      };
      axios({
        url: "/addCart",
        method: "get",
        params: params,
      }).then((res) => {
        console.log(res.data);
        if (res.data.code == 200) {
          ElNotification({
            title: "成功",
            message: "加入购物车成功",
            type: "success",
            duration: 2000,
          });
          // state.goodsDetail = res.data.data
        }
      });
    }
  };
  return {
    addcart,
  };
}

// 购买
function useAddOrder(state) {
  const addorder = () => {
    if (state.username == null) {
      ElNotification({
        title: "请先登录",
        message: "请先登录",
        type: "error",
        duration: 2000,
      });
    } else {
      //下单预览
      state.preOrderVisible = true;

    }
  };
  return {
    addorder,
  };
}
function getfa(state) {
  if (state.username != null) {

    axios({
      url: '/getFavorites',
      method: 'get',
      params: {
        username: state.username
      },
    }).then(res => {
      // console.log(res.data.data)
      var f = res.data.data;
      var i = 0;
      for (i; i < f.length; i++) {
        if (state.id == f[i].gid) {
          state.isF = 1
        }
      }
    })
  }
}

//收藏按钮
function usegoodsFavoritesByGid(state) {
  const goodsFavoritesByGid = (flag) => {
    if (state.username == null) {
      ElNotification({
        title: "请先登录",
        message: "请先登录",
        type: "error",
        duration: 2000,
      });
    } else {
      const params = {
        gid: state.id,
        username: state.username,
        id: '',
        flag: flag,
      }
      console.log(state.id)
      console.log(flag)
      axios({
        url: '/goodsFavoritesByGid',
        methods: 'get',
        params: params,
      }).then(res => {
        // loadData(state)
        if (res.data.code == 200) {
          ElNotification({
            title: "成功",
            message: "收藏成功",
            type: "success",
            duration: 2000,
          });
          getfa(state)
          // loadData(state)
          // location.reload();
        }
      })

    }
  }
  return {
    goodsFavoritesByGid,
  }
}
//取消收藏
function usegoodsUnFavoritesByGid(state) {
  const goodsUnFavoritesByGid = (flag) => {
    if (state.username == null) {
      ElNotification({
        title: "请先登录",
        message: "请先登录",
        type: "error",
        duration: 2000,
      });
    } else {
      const params = {
        gid: state.id,
        username: state.username,
        // id: '',
        // flag: flag,
      }
      // console.log(state.id)
      // console.log(flag)
      axios({
        url: '/goodsUnFavoritesByGid',
        methods: 'get',
        params: params,
      }).then(res => {
        // console.log(res.data)
        if (res.data.code == 200) {
          ElNotification({
            title: "成功",
            message: "取消收藏成功",
            type: "success",
            duration: 2000,
          });
          state.isF = 0;
          loadData(state)
          // getfa(state)
          // location.reload();
        }
      })
    }
  }
  return {
    goodsUnFavoritesByGid,
  }
}

//显示评论
function usegetMessage(state) {
  const params = {
    gid: state.id,
  };
  axios({
    url: "/getMessage",
    methods: "get",
    params: params,
  }).then((res) => {
    var u = res.data.data;
    var i = 0;
    state.Messagelist = [];
    for (i; i < u.length; i++) {
      state.Messagelist.push(u[i]);
    }
  });
}

//提交评论
function useaddMessage(state) {
  const addmessage = () => {
    if (state.username == null) {
      ElNotification({
        title: "请先登录",
        message: "请先登录",
        type: "error",
        duration: 2000,
      });
    } else {
      const params = {
        title: state.content,
        gid: state.id,
        username: state.username,
      };
      if (state.content != '') {
        axios({
          url: "/addMessage",
          methods: "get",
          params: params,
        }).then((res) => {
          console.log(res.data);
          if (res.data.code == 200) {
            ElNotification({
              title: "成功",
              message: "评价成功",
              type: "success",
              duration: 2000,
            });
            usegetMessage(state);
          } else {
            ElNotification({
              title: "评价失败",
              message: "你还没有购买此商品，在此之前不能评价",
              type: "error",
              duration: 3000,
            });
          }
        });
      } else {
        ElNotification({
          title: "评价失败",
          message: "内容不能为空",
          type: "error",
          duration: 2000,
        });
      }
    }
  };
  return {
    addmessage,
  };
}

//修改数量
function handleChange(state) {
  const handleChange = (value) => {
    state.num = value;
  };
  return {
    handleChange,
  };
}

export default {
  components: {
    preOrder,
  },

  inject: ["reload"],
  setup() {
    const $route = useRoute();

    // var id=$route.query.name

    const state = reactive({
      Messagelist: [],
      goodsDetail: [],
      imgU: "",
      content: "",
      id: $route.query.id,
      num: 1,
      aid: "",
      isF: '',
      username: JSON.parse(sessionStorage.getItem("token")),
      preOrderVisible: false,
    });

    const closePreOrderDialogVisible=(visible)=>{
            state.preOrderVisible = visible;
            // if(data !==undefined){
            //     loadData(state);
            // }
        };

    if (state.username != null) {

      axios({
        url: "/userAddressShow",
        method: "get",
        params: {
          username: state.username,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          state.aid = res.data.data[1].id;
        } else {
          console('查询用户地址失败')
          ElNotification({
            title: "失败",
            message: "查询用户地址失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    }
    // const imagesURL = import.meta.env.VITE_APP_URL + "/images/";
    onMounted(() => {
      loadData(state);
    });

    return {
      ...toRefs(state),
      ...getfa(state),
      ...usegoodsFavoritesByGid(state),
      ...usegoodsUnFavoritesByGid(state),
      // imagesURL,
      ...useAddcart(state),
      ...useAddOrder(state),
      // ...addmessage(state),
      ...usegetMessage(state),
      ...useaddMessage(state),
      url: "",
      srcList: ["{{ goodsDetail.picture }}"],
      closePreOrderDialogVisible,
      ...handleChange(state),
    };
  },
  methods: {
    // handleChange(value) {
    //   console.log(value);
    // },
  },
};
</script>

<style>
.goods {
  margin-top: 150px;
}
.img {
  float: left;
  border-radius: 0px;
  border-color: black;
}
.goodsdetail {
  width: 70%;
  height: 500px;
  margin: auto;
}
/* .ziti{
    float: right;
  } */
.join {
  color: white;
  margin: 10px 50px;
}
.buyin {
  color: white;
  margin: 10px 50px;
}
.hide {
  color: white;
  margin: 10px 150px;
}
.text-primary {
  color: blue;
}
.ul,
li {
  list-style: none;
}
.li {
  float: left;
}
.input {
  text-align: center;
  margin: 20px 0 50px 0;
}
.row {
  float: right;
}
.form-group {
  margin: auto;
  width: 70%;
}
</style>
